import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {environment} from '../../../environments/environment';
import {Login, SystemRes, VerifyCodeInfo} from '../base.model';
import {HttpClient} from '@angular/common/http';
import {CommonTool} from '../../common/common.tool';
import {DomSanitizer} from '@angular/platform-browser';
import {Router} from '@angular/router';
import {BaseService} from '../base.service';
import {HTTP_URLS} from '../base-http.url';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  public validateForm: FormGroup;
  public system: SystemRes;
  public systemInfoMap: any;
  public verifyCodeInfo: VerifyCodeInfo;
  public openVerifyCode: boolean;

  constructor(private fb: FormBuilder,
              private http: HttpClient,
              private commonTool: CommonTool,
              private sanitizer: DomSanitizer,
              public baseService: BaseService,
              private router: Router) {
    this.system = JSON.parse(sessionStorage.getItem(environment.systemInfo));
    this.systemInfoMap = {};
    this.verifyCodeInfo = new VerifyCodeInfo();
    for (const systemInfo of this.system.systemInfoList) {
      this.systemInfoMap[systemInfo.code] = systemInfo.value;
    }
    this.openVerifyCode = false;
  }


  ngOnInit(): void {
    this.validateForm = this.fb.group({
      account: [null, [Validators.email, Validators.required]],
      password: [null, [Validators.required, Validators.minLength(6)]],
      remember: [false],
      verifyCode: [null]
    });
  }

  /**
   * 失去焦点事件
   */
  public verifyAccount() {
    if (this.validateForm.controls.account.status === 'VALID') {
      this.baseService.verifyAccount({account: this.validateForm.controls.account.value}).subscribe((res) => {
        if (res.openVerifyCode) {
          this.openVerifyCode = res.openVerifyCode;
          this.verifyCode();
        }
        this.validateForm.controls['account'].setValidators(
          [Validators.email, Validators.required, function (control: FormControl) {
            if (!control.value) {
              return {required: true};
            } else if (!res.accountCorrect) {
              return {confirm: true};
            }
            return {};
          }]);
        this.validateForm.controls.account.markAsDirty();
        this.validateForm.controls.account.updateValueAndValidity();
      });
    }
  }

  /**
   * 输入事件
   */
  public keydown() {
    this.validateForm.controls['account'].setValidators([Validators.email, Validators.required]);
    this.validateForm.controls.account.markAsDirty();
    this.validateForm.controls.account.updateValueAndValidity();
  }

  /**
   * 获取验证码
   */
  public verifyCode() {
    this.http.get(HTTP_URLS.getVerifyCode + '?date=' + new Date().getTime()).subscribe(res => {
      this.verifyCodeInfo = new VerifyCodeInfo(res);
      const url = URL.createObjectURL(this.commonTool.dataURItoBlob(this.verifyCodeInfo.imgBytes));
      this.verifyCodeInfo.imgUrl = this.sanitizer.bypassSecurityTrustResourceUrl(url);
    });
  }

  /**
   * 提交
   */
  public submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.status === 'VALID') {
      if (this.openVerifyCode) {
        this.verifyCode();
      }
      const req: Login = new Login(this.validateForm.getRawValue());
      req.code = this.verifyCodeInfo.code;
      this.baseService.login(req).subscribe(res => {
        sessionStorage.setItem(environment.systemToken, JSON.stringify(res));
        this.commonTool.setCookie(environment.systemToken, res['token']);
        this.router.navigate(['/home']);
      });
    }
  }


}
